<template>
	<div class="pound-container">
		<div class="pound-bottom">
			<el-card>
				<template #header>
					<div style="display: flex;justify-content: space-between;">
						<div class="card-header" style="font-size: 24px;font-weight: 550;">
							<span>货物列表</span>
						</div>
						<div>
							<el-icon :size="28" @click="newlist">
								<Plus />
							</el-icon>
						</div>
					</div>
				</template>
				
				<div class="search-container"
					style="margin-bottom: 16px; display: flex; gap: 16px; align-items: center;">
					<!-- 货物名称检索 -->
					<el-form-item label="货物名称" style="margin-bottom: 0;">
						<el-input v-model="searchForm.cargoName" placeholder="请输入货物名称" style="width: 200px;"
							clearable />
					</el-form-item>

					<!-- 规格检索 -->
					<el-form-item label="规格" style="margin-bottom: 0;">
						<el-input v-model="searchForm.specifications" placeholder="请输入规格" style="width: 200px;"
							clearable />
					</el-form-item>

					<!-- 操作按钮 -->
					<div style="margin-left: auto;">
						<el-button type="primary" @click="fetchData">查询</el-button>
						<el-button @click="resetSearch">重置</el-button>
					</div>
				</div>
				
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="createTime" label="创建时间" width="200" />
					<el-table-column prop="cargoName" label="货物名称" />
					<el-table-column prop="specifications" label="规格" />
					<el-table-column prop="isEnable" label="启用" width="200">
						<template #default="scope">
						<el-switch 
						      v-model="scope.row.isEnable" 
						      active-value="1"  
						      inactive-value="0" 
						      active-text="启用"
						      inactive-text="禁用" 
						      @change="(value) => handleStatusChange(scope.row, value)" 
						      style="margin-left: 8px;" 
						    />
						</template>	
					</el-table-column>
					<el-table-column label="操作" width="150" fixed="right">
						<template #default="scope">
							<el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="total>0" v-model:current-page="listQuery.current"
						v-model:page-size="listQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>
		</div>

		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
			<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item label="货物名称" prop="cargoName">
					<el-input v-model="formData.cargoName" placeholder="请输入货物名称" style="width: 180px;" />
				</el-form-item>

				<el-form-item label="规格" prop="specifications">
					<el-input v-model="formData.specifications" placeholder="请输入规格" style="width: 180px;" />
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button @click="resetForm">取消</el-button>
				<el-button type="primary" @click="handleSubmit">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
	import {
		ref,
		nextTick ,
		reactive,
		onMounted,
		getCurrentInstance
	} from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import { useRouter } from 'vue-router'
	
	const { proxy } = getCurrentInstance()!;
	const router = useRouter()
	const dialogVisible = ref(false)
	const formRef = ref<FormInstance>()
	const dialogTitle = ref('新增货物')
	const currentEditId = ref<number | null>(null)
	const actionType = ref('add')
	
	const searchForm = reactive({
		cargoName: '',
		specifications: ''
	});
	
	const defaultFormData = {
		id: null,
		cargoName: '',
		specifications: '',
	}
	
	const formData = reactive({ ...defaultFormData })

	const rules = reactive<FormRules>({
		cargoName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }]
	})
	
	const cargoOptions = ref<any[]>([])
	
	const resetSearch = () => {
		searchForm.cargoName = '';
		searchForm.specifications = '';
		listQuery.current = 1;
		fetchData();
	};

	const handleCargoChange = (val : string, formData : Record<string, any>) => {
		const matchingCargo = cargoOptions.value.find(
			(cargo) => formData.cargoName === cargo.cargoName
		);

		if (matchingCargo) {
			formData.specifications = matchingCargo.specifications;
		}

		if (!cargoOptions.value.some(item => item.id === val)) {
			cargoOptions.value.push({
				cargoName: val,
				id: val
			})
		}
	}
	
	const resetForm = () => {
		formRef.value?.resetFields()
		Object.assign(formData, defaultFormData)
		dialogVisible.value = false
	}
	
	// 修复后的状态变更处理函数 - 确保询问用户并发送请求
	const handleStatusChange = async (row: any, newValue: string) => {
		// 1. 初始化时的触发直接忽略，仅重置标记
		if (row._isInitializing) {
			row._isInitializing = false;
			return;
		}
		
		// 2. 确保状态值正确
		const newStatus = newValue;
		const oldStatus = newStatus === '1' ? '0' : '1';
		
		// 3. 禁用操作需要确认
		if (newStatus === '0') {
			try {
				// 显示确认对话框
				await ElMessageBox.confirm(
					'确定要禁用该货物吗？禁用后将无法正常使用相关功能！',
					'禁用确认',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}
				);

				// 用户确认后发送请求
				console.log('发送禁用请求，ID:', row.id, '新状态:', newStatus);
				const res = await proxy.$request.setRule({
					id: row.id,
					isEnable: newStatus
				});

				if (res?.data?.code === 200) {
					ElMessage.success('禁用成功！');
					row.isEnable = newStatus; // 更新状态
				} else {
					// 请求失败回滚状态
					row.isEnable = oldStatus;
					ElMessage.error(res?.data?.message || '禁用失败，请重试');
				}

			} catch (error) {
				// 用户取消或请求失败都回滚状态
				row.isEnable = oldStatus;
				// 排除用户主动取消的情况，不显示错误
				if (!(error as any).message.includes('cancel')) {
					ElMessage.error('操作失败，请检查网络');
				}
			}
		} else {
			// 4. 启用操作直接发送请求
			try {
				console.log('发送启用请求，ID:', row.id, '新状态:', newStatus);
				const res = await proxy.$request.setRule({
					id: row.id,
					isEnable: newStatus
				});
				
				if (res?.data?.code === 200) {
					ElMessage.success('启用成功！');
					row.isEnable = newStatus; // 更新状态
				} else {
					row.isEnable = oldStatus; // 回滚状态
					ElMessage.error(res?.data?.message || '启用失败，请重试');
				}
			} catch (error) {
				row.isEnable = oldStatus; // 回滚状态
				ElMessage.error('操作失败，请检查网络');
			}
		}
	};
	
	const handleEdit = (row : any) => {
		actionType.value = 'edit'
		dialogTitle.value = '编辑货物'
		currentEditId.value = row.id

		Object.keys(formData).forEach(key => {
			if (row.hasOwnProperty(key)) {
				formData[key] = row[key]
			}
		})

		dialogVisible.value = true
	}
	
	const filterEmptyFields = (obj : any) => {
		return Object.entries(obj).reduce((acc, [key, value]) => {
			if (value !== '' && value !== null && value !== undefined) {
				acc[key] = value
			}
			return acc
		}, {})
	}
	
	const getCargoNameList = async () => {
		try {
			const res = await proxy.$request.getCargoNameList()
			cargoOptions.value = []
			if (res?.data?.code === 200 && res.data.result) {
				cargoOptions.value = res.data.result
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.message || '网络请求异常')
		}
	}

	const handleSubmit = async () => {
		try {
			await formRef.value?.validate()

			proxy.$request.setRule(formData).then((res: any) => {
				if (res.data.code === 200) {
					ElMessage.success(res.data.message)
					resetForm()
					fetchData()
				} else {
					ElMessage.error(res.data.message)
				}
			}).catch((err: any) => {
				console.log('err', err)
				ElMessage.error(err);
			})
		} catch (error) {
			console.log('表单验证失败:', error)
		}
	}

	defineExpose({
		open: () => {
			dialogVisible.value = true
			formRef.value?.resetFields()
		}
	})
	
	const newlist = () => {
		actionType.value = 'add'
		dialogTitle.value = '新增货物'
		resetForm()
		dialogVisible.value = true
	}
	
	const tableData = ref<any[]>([])
	const listQuery = reactive({
		current: 1,
		size: 5,
	})
	const total = ref(0)
	const size = ref<ComponentSize>('default')

	const fetchData = async () => {
		try {
			const queryParams = { ...listQuery, ...filterEmptyFields(searchForm) };
			const res = await proxy.$request.getDeductWeight(queryParams);

			if (res?.data?.code === 200) {
				const data = res.data.result?.resultData || [];
				nextTick(() => {
					// 添加初始化标记，避免初始加载时触发弹窗
					tableData.value = data.map(row => ({
						...row,
						// _isInitializing: true // 使用更明确的初始化标记
					}));
					total.value = res.data.result?.totalRows || 0;
				});
			} else {
				ElMessage.error(res?.data?.message || '请求失败');
			}
		} catch (error : any) {
			console.error('API请求错误:', error);
			ElMessage.error(error.message || '网络请求异常');
		}
	};

	const handleSizeChange = (val : number) => {
		listQuery.size = val;
		fetchData()
	}
	
	const handleCurrentChange = (val : number) => {
		listQuery.current = val;
		fetchData()
	}

	onMounted(() => {
		fetchData()
		getCargoNameList()
	})
</script>

<style lang="scss" scoped>
	.pound-container {
		padding: 28px;
		box-sizing: border-box;
		position: relative;

		.pound-bottom {
			width: 100%;
			margin-top: 50px;
		}

		.search-container {
			flex-wrap: wrap;
			padding: 8px 0;

			@media (max-width: 768px) {
				el-form-item {
					width: 100%;
					margin-bottom: 8px !important;
				}

				el-input {
					width: 100% !important;
				}
			}
		}
	}
</style>
